<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "dorminfo".
 *
 * @property string $stu_id
 * @property integer $dorm_area
 * @property string $dormitory
 * @property string $dorm_num
 * @property string $stu_name
 * @property string $leader
 */
class DorminfoModel extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'dorminfo';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['stu_id','dorm_area','dormitory','dorm_num'], 'required'],
            [['stu_id'], 'unique'],
            [['dorm_area'], 'integer'],
            [['stu_id'], 'string', 'max' => 20],
        		[['stu_name'], 'string', 'max' => 50],
            [['dormitory', 'dorm_num'], 'string', 'max' => 10],
            [['leader'], 'safe'],
        ];
    }
    
    
    
    public function beforeSave($insert)
    {
    	if (parent::beforeSave($insert)) {
    		// Place your custom code here
    		if($this->leader !=='无') //注意这里是配合视图中“未选择”选项做判断
    			$this->leader = implode(',', $this->leader);
    			return true;
    	} else {
    		return false;
    	}
    }
    
    

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'stu_id' => '学号',
        		'stu_name'=>'姓名',
            'dorm_area' => '宿舍区',
            'dormitory' => '宿舍楼',
            'dorm_num' => '宿舍号',
            'leader' => '宿舍管理学生干部',
        ];
    }

    /**
     * 保存导入excel文件内容
     * @param $data  传入文件内容的数组
     * @return bool  保存成功返回true
     *
     */
    public static function SaveImport($data){

        try{

            foreach ($data as $value){

                $person=new DorminfoModel();
                $person->stu_id=$value['学号'].'';//学号要转化为字符型才能通过验证
                $person->stu_name=$value['姓名'].'';
                $person->dorm_area=(int)$value['宿舍区'].'';
                $person-> dormitory=$value['宿舍楼'].'';
                $person->dorm_num=$value['宿舍号'].'';
                $person->leader=$value['宿舍管理学生干部'].'';

                $person->save();
            }
            return true;

        }catch (\Exception $e){
            throw $e;
        }

    }

}
